package sixkey.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sixkey.annotation.Log;
import sixkey.listener.EventPublistener;
import sixkey.utils.IpUtils;
import springfox.documentation.RequestHandler;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * ClassName:SysLogAspect
 * Package:sixkey.aop
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/7/13 - 1:49
 * @Version:v1.0
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    @Pointcut("@annotation(sixkey.annotation.Log)")
    public void pointcut(){}

    @Autowired
    private EventPublistener eventPublistener;

    /**
     * 在切点之后切入
     */
    @After("pointcut()")
    public void deAfter(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取方法上的注解
        Log logAnnotation = method.getAnnotation(Log.class);

        //获取系统基本信息

         ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestMethod = request.getMethod();
        String url = request.getRequestURI().toString();
        String ip = IpUtils.getIpAddr(request);
        sixkey.domain.entity.Log sysLog = new sixkey.domain.entity.Log();
        sysLog.setBusinessType(logAnnotation.businessType().getCode());
        sysLog.setTitle(logAnnotation.title());
        sysLog.setRequestMethod(requestMethod);
        sysLog.setOperIp(ip);
        sysLog.setOperUrl(url);
        //从登录中token获取登录人员信息即可
        sysLog.setOperName("我是测试人员");
        sysLog.setOperTime(LocalDateTime.now());
        //发布消息
        eventPublistener.publishEvent(sysLog);
        log.info("========日志发送成功，内容为：{}==========",sysLog);
    }
}
